package controllers

import (
	"net/http"
	"rbac-system/database"
	"rbac-system/models"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetPermissions(c *gin.Context) {
	var permissions []models.Permission
	query := database.DB

	// 搜索条件
	if name := c.Query("name"); name != "" {
		query = query.Where("name LIKE ?", "%"+name+"%")
	}
	if code := c.Query("code"); code != "" {
		query = query.Where("code LIKE ?", "%"+code+"%")
	}
	if permType := c.Query("type"); permType != "" {
		query = query.Where("type = ?", permType)
	}

	// 分页
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	offset := (page - 1) * pageSize

	var total int64
	query.Model(&models.Permission{}).Count(&total)

	if err := query.Offset(offset).Limit(pageSize).Find(&permissions).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询权限失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data":  permissions,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

func GetPermission(c *gin.Context) {
	id := c.Param("id")
	var permission models.Permission

	if err := database.DB.First(&permission, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "权限不存在"})
		return
	}

	c.JSON(http.StatusOK, permission)
}

func CreatePermission(c *gin.Context) {
	var req struct {
		Name        string `json:"name" binding:"required"`
		Code        string `json:"code" binding:"required"`
		Description string `json:"description"`
		Type        int    `json:"type" binding:"required"`
		ParentID    uint   `json:"parent_id"`
		Path        string `json:"path"`
		Method      string `json:"method"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	// 检查权限码是否已存在
	var existingPermission models.Permission
	if err := database.DB.Where("code = ?", req.Code).First(&existingPermission).Error; err == nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "权限码已存在"})
		return
	}

	permission := models.Permission{
		Name:        req.Name,
		Code:        req.Code,
		Description: req.Description,
		Type:        req.Type,
		ParentID:    req.ParentID,
		Path:        req.Path,
		Method:      req.Method,
	}

	if err := database.DB.Create(&permission).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建权限失败"})
		return
	}

	c.JSON(http.StatusCreated, permission)
}

func UpdatePermission(c *gin.Context) {
	id := c.Param("id")
	var permission models.Permission

	if err := database.DB.First(&permission, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "权限不存在"})
		return
	}

	var req struct {
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
		Type        int    `json:"type" binding:"required"`
		ParentID    uint   `json:"parent_id"`
		Path        string `json:"path"`
		Method      string `json:"method"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	permission.Name = req.Name
	permission.Description = req.Description
	permission.Type = req.Type
	permission.ParentID = req.ParentID
	permission.Path = req.Path
	permission.Method = req.Method

	if err := database.DB.Save(&permission).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新权限失败"})
		return
	}

	c.JSON(http.StatusOK, permission)
}

func DeletePermission(c *gin.Context) {
	id := c.Param("id")
	var permission models.Permission

	if err := database.DB.First(&permission, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "权限不存在"})
		return
	}

	// 检查是否有角色关联此权限
	var roleCount int64
	database.DB.Model(&models.Role{}).Where("id IN (SELECT role_id FROM role_permissions WHERE permission_id = ?)", id).Count(&roleCount)
	if roleCount > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该权限已被角色使用，无法删除"})
		return
	}

	if err := database.DB.Delete(&permission).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除权限失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "权限删除成功"})
}

func GetPermissionTree(c *gin.Context) {
	var permissions []models.Permission
	if err := database.DB.Order("parent_id, id").Find(&permissions).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询权限树失败"})
		return
	}

	// 构建树形结构
	permissionMap := make(map[uint]*models.Permission)
	for i := range permissions {
		permissionMap[permissions[i].ID] = &permissions[i]
	}

	var tree []map[string]interface{}
	for _, perm := range permissions {
		if perm.ParentID == 0 {
			node := map[string]interface{}{
				"id":          perm.ID,
				"name":        perm.Name,
				"code":        perm.Code,
				"description": perm.Description,
				"type":        perm.Type,
				"path":        perm.Path,
				"method":      perm.Method,
				"children":    []map[string]interface{}{},
			}
			tree = append(tree, node)
		}
	}

	// 添加子节点
	for _, perm := range permissions {
		if perm.ParentID != 0 {
			for i := range tree {
				if tree[i]["id"] == perm.ParentID {
					child := map[string]interface{}{
						"id":          perm.ID,
						"name":        perm.Name,
						"code":        perm.Code,
						"description": perm.Description,
						"type":        perm.Type,
						"path":        perm.Path,
						"method":      perm.Method,
					}
					children := tree[i]["children"].([]map[string]interface{})
					children = append(children, child)
					tree[i]["children"] = children
					break
				}
			}
		}
	}

	c.JSON(http.StatusOK, tree)
}
